<template>
  <div>
    <div style="display: inline">
    <el-input
        placeholder="搜索..."
        size="mini"
        style="width: 300px;margin: 0px;padding: 0px;">
    </el-input>
    <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-search">搜索
    </el-button>      
    <el-button type="primary" size="mini" icon="el-icon-plus" @click="showAddUserView">添加用户
    </el-button>      
      
    </div>
    <el-table
      ref="multipleTable"
      :data="userList.slice((currentPage-1)*pageSize,currentPage*pageSize)"
      tooltip-effect="dark"
      style="width: 100%"
      stripe
      border
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        width="200">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
        width="200">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="电话"
        width="200">
      </el-table-column>
      <el-table-column
        prop="dept.name"
        label="所属部门"
        width="200">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="200"
        sortable>
      </el-table-column>
      <el-table-column 
        label="操作"
        width="200">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="userList.length">
      </el-pagination>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input v-model="form.checkPassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" type="email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-input v-model="form.deptId"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-checkbox-group v-model="checkedRoles" size="medium" @change="handleCheckedChange">
            <el-checkbox v-for="role in roleList" :label="role.id" :key="role.id" border>{{role.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addUser(form)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
  
</template>

<script>
  export default {
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.form.checkPassword !== '') {
            this.$refs.form.validateField('checkPassword');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.form.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        userList: [],
        roleList: [],
        checkedRoles: [],
        currentPage: 1,
        pageSize: 20,
        multipleSelection: [],
        dialogTitle: '',
        dialogVisible: false,
        form: {
          username: '',
          password: '',
          checkPassword: '',
          email: '',
          phone: '',
          deptId: 1,
          roleIds: [],
        },
        index: '',
        row: '',
        rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 2, max: 11, message: '长度在 2 到 11 个字符', trigger: 'blur' }
          ],
          password: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPassword: [
            { validator: validatePass2, trigger: 'blur' }
          ],
          email: [
            { required: true, message: '邮箱', trigger: 'change' },
            { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式有误'}
          ],
          phone: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号码' }
          ],
          deptId: [
            { required: true, message: '部门', trigger: 'change' }
          ],
        }
      }
    },

    created () {
      // 组件创建完后获取数据，
      // 此时 data 已经被 observed 了
      this.getUserList();
      this.getRoleList();
    },

    // watch: {
    //   // 如果路由有变化，会再次执行该方法
    //   '$route': 'getUserList'
    // },

    methods: {
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleEdit(index, row) {
        let roles = row.roles;
        console.log('---->roles：' + JSON.stringify(roles));
        let roleIds = [];
        for (let index in roles) {
          let id = roles[index].id;
          roleIds.push(id);
        }
        
        this.form.roleIds = roleIds;
        this.checkedRoles = roleIds;
        this.form.username = row.username;
        this.form.password = row.password;
        this.form.checkPassword = row.password;
        this.form.phone = row.phone;
        this.form.email = row.email;
//        delete this.user.checkPassword;
        this.dialogTitle = "编辑用户";
        this.dialogVisible = true;
        this.index = index;
        this.row = row;
      },
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除[' + row.username + '], 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteRequest("/user/" + row.id).then(data=> {
            this.$message({
              message: '删除用户成功',
              type: 'success'
            });
            this.userList.splice(index, 1);
          })
        })
        
      },
      handleSizeChange(size) {
        this.pageSize = size;
      },
      handleCurrentChange(currentPage){
        this.currentPage = currentPage;
      },
      getUserList(){
        this.getRequest("/user").then(data=> {
            this.userList = data;
        })
      },
      getRoleList(){
        this.getRequest("/role").then(data=> {
            this.roleList = data;
        })
      },
      showAddUserView(){
        this.initFormData();
        this.dialogTitle = "添加用户";
        this.dialogVisible = true;
      },
      addUser(form){
        var _this = this;
        this.$refs.form.validate((valid) => {
          if (valid) {
            _this.dialogVisible = false;
            let userForm = {};
            userForm.username = this.form.username;
            userForm.password = this.form.password;
            userForm.email = this.form.email;
            userForm.phone = this.form.phone;
            userForm.deptId = this.form.deptId;
            userForm.roleIds = this.checkedRoles;
            if (!this.row.id) {
              //添加
              this.postRequest("/user", JSON.stringify(userForm)).then(data=> {
                this.$message({
                  message: '添加成功，新增的用户为：' +　data.username,
                  type: 'success'
                });
                this.userList.push(data);
                _this.dialogVisible = false;
              })              
            }else{
              userForm.id = this.row.id;
              //修改
              this.putRequest("/user/" + userForm.id, JSON.stringify(userForm)).then(data=> {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.userList.splice(this.index, 1, data);
                this.index = '';
                this.row = '';
                _this.dialogVisible = false;
              })              
            }
            
          } else {
            this.$message({
              message: '操作失败',
              type: 'error'
            });
            return false;
          }
        });
      },
      cancel(){
        this.dialogVisible = false;
        this.initFormData();
      },
      initFormData(){
        this.form = {
          username: '',
          password: '',
          email: '',
          phone: '',
          deptId: 1,
        };
        this.checkedRoles = [];
      },

      handleCheckedChange(){
        console.log(this.checkedRoles);
      }

    }
  }
</script>